package io.zcoder.innoway.activities;

import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.StringDef;
import android.view.View;
import android.view.WindowManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.zcoder.innoway.R;
import io.zcoder.innoway.utils.Utils;
import io.zcoder.innoway.commons.Constants;
import io.zcoder.innoway.commons.PrefUtils;
import io.zcoder.innoway.models.ProfileDetailResponse;
import io.zcoder.innoway.rest.RestClient;
import io.zcoder.innoway.widgets.EditTextCustom;
import io.zcoder.innoway.widgets.ScrollSelectRelationView;
import io.zcoder.innoway.widgets.TextViewCustom;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class AddProfileActivity extends BaseActivity {
    public static final int MALE = 0;
    public static final int FEMALE = 1;
    public static final int REQUEST_SET_PASS_CODE = 123;
    public static final int REQUEST_SET_AGE = 124;
    public static final int REQUEST_SET_HEIGHT = 125;
    private static final long DURATION_TRANSLATION_GENDER = 400;
    public static final String EXTRA_PROFILE_ID = "profile_id";

    private int profileId;

    @BindView(R.id.select_gender)
    TextViewCustom mGenderSelect;
    @BindView(R.id.first_name)
    EditTextCustom mFirstName;
    @BindView(R.id.last_name)
    EditTextCustom mLastName;
    @BindView(R.id.pascode)
    TextViewCustom mPasscode;
    @BindView(R.id.height)
    TextViewCustom mHeightView;
    @BindView(R.id.age)
    TextViewCustom mAgeView;
    @BindView(R.id.txt_relation)
    TextViewCustom mTxtRelation;
    @BindView(R.id.relation)
    ScrollSelectRelationView mRelationView;

    @OnClick(R.id.finish)
    void finishBtn() {
        if (mFirstName.isEmpty() || mLastName.isEmpty() || mHeightView.isEmpty() || mAgeView.isEmpty()) {
            showAlert(getString(R.string.error), getString(R.string.error_empty));
        } else {
            submit();
        }
    }

    @OnClick(R.id.pascode)
    void onPasscode() {
        Intent intent = new Intent(this, InputPassCodeActivity.class);
        startActivityForResult(intent, REQUEST_SET_PASS_CODE);
    }

    @OnClick(R.id.height)
    void editHeight() {
        Intent intent = new Intent(this, SelectTallActivity.class);
        intent.putExtra(Constants.EDIT_INFO_EXTRAS, true);
        startActivityForResult(intent, REQUEST_SET_HEIGHT);
    }

    @OnClick(R.id.age)
    void editAge() {
        Intent intent = new Intent(this, SelectBirthDayActivity.class);
        intent.putExtra(Constants.EDIT_INFO_EXTRAS, true);
        startActivityForResult(intent, REQUEST_SET_AGE);
    }

    @OnClick(R.id.layout_select_gender)
    void clickGender() {
        selectGender();
    }

    private int mCurrentGender = MALE;
    private Point mPoint = new Point();
    private String mBirthday;
    private int mHeight;
    private float mTypeHeight;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_add_profile_activity);
        ButterKnife.bind(this);
        showBack(true);
        setTitle(getString(R.string.add_member));
        profileId = getIntent().getIntExtra(EXTRA_PROFILE_ID, 0);
        if (profileId != 0) {
            mTxtRelation.setVisibility(View.GONE);
            mRelationView.setVisibility(View.GONE);
            mBack.setVisibility(View.GONE);
        }
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getSize(mPoint);
    }

    void selectGender() {
        if (mCurrentGender == MALE) {
            mGenderSelect.animate().setDuration(DURATION_TRANSLATION_GENDER).translationX(mPoint.x / 2 - getResources().getDimension(R.dimen.dp15));
            mGenderSelect.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mGenderSelect.setText(R.string.female);
                }
            }, DURATION_TRANSLATION_GENDER - 100);
            mCurrentGender = FEMALE;
        } else {
            mGenderSelect.animate().setDuration(DURATION_TRANSLATION_GENDER).translationX(0);
            mGenderSelect.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mGenderSelect.setText(R.string.male);
                }
            }, DURATION_TRANSLATION_GENDER - 100);
            mCurrentGender = MALE;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_SET_PASS_CODE && resultCode == InputPassCodeActivity.RESPONSE_SET_PASS_CODE) {
            String passcode = data.getStringExtra(Constants.PASS_CODE_EXTRAS);
            if (!Utils.isBlank(passcode)) {
                mPasscode.setText(passcode);
            }
        }
        if (requestCode == REQUEST_SET_HEIGHT && resultCode == SelectTallActivity.RESULT_SET_TALL) {
            mTypeHeight = data.getIntExtra(Constants.TYPE_TALL_EXTRAS, 0);
            mHeight = (int) data.getFloatExtra(Constants.TALL_EXTRAS, 0);
            if (mTypeHeight == SelectTallActivity.TYPE_CM) {
                mHeightView.setText(mHeight + " cm");
            } else if (mTypeHeight == SelectTallActivity.TYPE_FT) {
                mHeightView.setText(Utils.convertToInch(mHeight));
            }
        }
        if (requestCode == REQUEST_SET_AGE && resultCode == SelectBirthDayActivity.RESULT_SET_BIRTHDAY) {
            mBirthday = data.getStringExtra(Constants.BIRTHDAY_EXTRAS);
            int age = data.getIntExtra(Constants.AGE_EXTRAS, -1);
            if (age != -1) {
                mAgeView.setText(age + "");
            }
        }
    }

    private void submit() {
        showProgress();
        if (profileId != 0) {
            RestClient.build(this, true).updateProfile(profileId, mFirstName.getString(), mLastName.getString(),
                    mPasscode.getString(), mHeight, mCurrentGender == MALE, mBirthday,
                    new Callback<ProfileDetailResponse>() {
                        @Override
                        public void success(ProfileDetailResponse profileDetailResponse, Response response) {
                            hideProgress();
                            if (profileDetailResponse.getStatus_code() != 200) {
                                showAlert(getString(R.string.error), profileDetailResponse.getMessage());
                            } else {
                                PrefUtils.setInt(AddProfileActivity.this, PrefUtils.PREF_PROFILE_ID, profileDetailResponse.getData().getId());
                                Intent intent = new Intent(AddProfileActivity.this, TopActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                            }
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            hideProgress();
                        }
                    });
        } else {
            RestClient.build(this, true).addProfile(mFirstName.getString(), mLastName.getString(),
                    mPasscode.getString(), mHeight, mCurrentGender == MALE, mBirthday, mRelationView.getIndex(),
                    new Callback<ProfileDetailResponse>() {
                        @Override
                        public void success(ProfileDetailResponse profileDetailResponse, Response response) {
                            hideProgress();
                            if (profileDetailResponse.getStatus_code() != 200) {
                                showAlert(getString(R.string.error), profileDetailResponse.getMessage());
                            } else {
                                setResult(RESULT_OK);
                                PrefUtils.setInt(AddProfileActivity.this, PrefUtils.PREF_PROFILE_ID, profileDetailResponse.getData().getId());
                                finish();
                            }
                        }

                        @Override
                        public void failure(RetrofitError error) {
                            hideProgress();
                        }
                    });

        }

    }
}
